<template>
  <div class="box">
    <h2>子组件 add</h2>
    <!-- $store可以获取到vuex实例在上面获取数据 -->
    从vuex中获取的值:<label>{{count}} ---- listLength: {{$store.getters.listLength}}---{{listLength}}</label>
    <br />
    <button @click="addCount">值+1</button>
    <button @click="addN(5)">值+n</button>
    <button @click="setAsyncCount">3秒之后+1</button>
    <button @click="setAsyncCountN(5)">1秒之后+n</button>
  </div>
</template>

<script>
import { mapMutations, mapActions, mapGetters } from 'vuex'
export default {
  name: 'AddItem',
  // 可以利用计算属性获取state上的数据
  // mapGetters放在computed中
  computed: {
    ...mapGetters(['listLength']),
    // listLength() {
    //   return this.$store.getters.listLength
    // },
    count () {
      return this.$store.state.count
    },
    car () {
      return this.$store.state.car
    }
  },
  mounted () {
    console.log(this.$store)
  },
  methods: {
    ...mapMutations(['addCount', 'addN']),
    ...mapActions(['setAsyncCount', 'setAsyncCountN'])
    // add () {
    //   // 提交mutation是唯一可以改变state数据的途径 commit(mutation的名字)
    //   this.$store.commit('addCount')
    // },
    // addN (num) {
    //   // const obj = {
    //   //   car: '小黄车',
    //   //   num: num
    //   // }
    //   // this.$store.commit('addN', obj)
    //   this.$store.commit('addN', num)
    // }
    // 触发actions   用  this.$store.dispatch(action的名字)
    // setAsyncCount () {
    //   this.$store.dispatch('setAsyncCount')
    // },
    // setAsyncCountN (num) {
    //   this.$store.dispatch('setAsyncCountN', num)
    // }
  }
}
</script>

<style lang="css" scoped>
.box {
  border: 3px solid #ccc;
  width: 400px;
  padding: 10px;
  margin: 20px;
}
h2 {
  margin-top: 10px;
}
</style>
